//
//  ScheduleBaseLite.m
//  FMS
//
//  Created by Steven on 10/20/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "ScheduleBaseLite.h"
#import "CouchBaseLiteLib.h"
#import "NSDate+DateTime.h"

@implementation ScheduleBaseLite

+ (NSString*) docType {
    return kScheduleDocType;
}

- (instancetype) initInDatabase:(CBLDatabase *)database withTitle:(NSString *)title
{
    self = [super initInDatabase:database withTitle: title];
    
    return self;
}

// Returns a query for all the lists in a database.
+ (NSMutableArray*) queryListsInDatabase: (CBLDatabase*)db {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double timeInterval = [[userDefaults objectForKey:TIME_DURATION_DB_SERVER] doubleValue];
    NSTimeInterval timeIntervalLimited = [[[NSDate date] dateByAddingTimeInterval:-timeInterval] timeIntervalSince1970];
    
    CBLView* view = [db viewNamed: @"listsSchedule"];
    if (!view.mapBlock) {
        // Register the map function, the first time we access the view:
        [view setMapBlock: MAPBLOCK({
            id startDate = [doc objectForKey:@"startDate"];
            if ([doc[@"Table"] isEqualToString:kScheduleDocType])
                emit(startDate, nil);
        }) reduceBlock: nil version: @"1.1"]; // bump version any time you change the MAPBLOCK body!
    }
    CBLQuery *query = [view query];
    query.descending = YES;
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (CBLQueryRow *row in query.rows) {
        double dateUpdated = [[row.document propertyForKey:@"dateUpdated"] doubleValue];
        if (dateUpdated >= timeIntervalLimited)
            [array addObject:[row.document.properties mutableCopy]];
    }
//    [array sortUsingComparator:^(NSMutableDictionary *obj1, NSMutableDictionary *obj2){
//        
//        NSDate *date1 = [NSDate dateFormatDateFullFromString:[obj1 objectForKey:@"startDate"]];
//                         
//        NSDate *date2 = [NSDate dateFormatDateFullFromString:[obj2 objectForKey:@"startDate"]];
//        if (date1 && date2)
//            return [date2 compare:date1];
//        else
//            return NSOrderedAscending;
//            
//    }];
    return array;
}

+ (NSMutableArray*) queryListsInDatabase: (CBLDatabase*)db byIdCategory:(int)categoryId{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double timeInterval = [[userDefaults objectForKey:TIME_DURATION_DB_SERVER] doubleValue];
    NSTimeInterval timeIntervalLimited = [[[NSDate date] dateByAddingTimeInterval:-timeInterval] timeIntervalSince1970];
    
    CBLView* view = [db viewNamed: @"listScheduleByCategoryId"];
    if (!view.mapBlock) {
        // Register the map function, the first time we access the view:
        [view setMapBlock: MAPBLOCK({
            if ([doc[@"Table"] isEqualToString:kScheduleDocType]){
                NSString *categoryId = doc[@"categoryId"];
                if (categoryId)
                    emit(categoryId, nil);
            }
        }) reduceBlock: nil version: @"1"]; // bump version any time you change the MAPBLOCK body!
    }
    
    CBLQuery *query = [view query];
    query.keys = @[[NSNumber numberWithInt:categoryId]];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (CBLQueryRow *row in query.rows) {
        double dateUpdated = [[row.document propertyForKey:@"dateUpdated"] doubleValue];
        if (dateUpdated >= timeIntervalLimited)
            [array addObject:[row.document.properties mutableCopy]];
    }
    
    [array sortUsingComparator:^(NSMutableDictionary *obj1, NSMutableDictionary *obj2){
        
        NSDate *date1 = [NSDate dateFormatDateFullFromString:[obj1 objectForKey:@"startDate"]];
        
        NSDate *date2 = [NSDate dateFormatDateFullFromString:[obj2 objectForKey:@"startDate"]];
        if (date1 && date2)
            return [date2 compare:date1];
        else
            return NSOrderedAscending;
        
    }];
    
    return array;
}

+ (NSMutableArray*) queryListsInDatabase: (CBLDatabase*)db byCategory:(NSMutableDictionary *)category{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double timeInterval = [[userDefaults objectForKey:TIME_DURATION_DB_SERVER] doubleValue];
    NSTimeInterval timeIntervalLimited = [[[NSDate date] dateByAddingTimeInterval:-timeInterval] timeIntervalSince1970];
    
    CBLView* view = [db viewNamed: @"listScheduleByCategoryIdAndType"];
    if (!view.mapBlock) {
        // Register the map function, the first time we access the view:
        [view setMapBlock: MAPBLOCK({
            if ([doc[@"Table"] isEqualToString:kScheduleDocType]){
                NSString *categoryId = [doc objectForKey:@"categoryId"];
                if (categoryId)
                   emit(@[categoryId,doc],nil);
            }
        }) reduceBlock: nil version: @"1"]; // bump version any time you change the MAPBLOCK body!
    }
    
    CBLQuery *query = [view query];
//    query.keys = @[@[[category objectForKey:@"categoryId"],[category objectForKey:@"categoryTypeId"]]];
//    query.startKey = @[[category objectForKey:@"categoryId"],[category objectForKey:@"maintenanceTypeId"]];
//    query.endKey = @[[category objectForKey:@"categoryId"],[category objectForKey:@"maintenanceTypeId"]];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (CBLQueryRow *row in query.rows) {
        double dateUpdated = [[row.document propertyForKey:@"dateUpdated"] doubleValue];
        if (dateUpdated >= timeIntervalLimited) {
            if ([[category objectForKey:@"categoryId"] intValue] == Inspection) {
                [array addObject:[row.document.properties mutableCopy]];
            }
            else{
                if ([[category objectForKey:@"categoryTypeId"] intValue] == [[row.document.properties objectForKey:@"maintenanceTypeId"] intValue]) {
                    [array addObject:[row.document.properties mutableCopy]];
                }
            }
        }
    }
    [array sortUsingComparator:^(NSMutableDictionary *obj1, NSMutableDictionary *obj2){
        
        NSDate *date1 = [NSDate dateFormatDateFullFromString:[obj1 objectForKey:@"startDate"]];
        
        NSDate *date2 = [NSDate dateFormatDateFullFromString:[obj2 objectForKey:@"startDate"]];
        if (date1 && date2)
            return [date2 compare:date1];
        else
            return NSOrderedAscending;
        
    }];
    return array;
}

// Returns a query for all the lists in a database.
+ (NSMutableArray*) queryScheduleInStart:(NSString *)startDate endDate:(NSString *)endDate from:(int)indexFrom  numberPage:(int)count{
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        NSDate *dateStart = nil;
        if (startDate != nil && ![startDate isEqualToString:@""]) {
            dateStart =[NSDate dateFormatDateDisplayFromString:startDate];
            
        }
        NSDate *dateEnd = nil;
        if (endDate != nil && ![endDate isEqualToString:@""]) {
            dateEnd = [NSDate dateFormatDateDisplayFromString:endDate];
        }
        
        for (NSMutableDictionary *dict in array) {
            @try {
                NSString *strDateSchedue = [dict objectForKey:@"startDate"];
                strDateSchedue = [strDateSchedue substringToIndex:10];
                NSDate *dateSchedule = [NSDate dateFormatDateFromString:strDateSchedue];
                BOOL isAdd = YES;
                
                if (dateStart && [dateStart compare:dateSchedule] == NSOrderedDescending) {
                    isAdd = NO;
                }
                if (isAdd && dateEnd && [dateEnd compare:dateSchedule] == NSOrderedAscending) {
                    isAdd = NO;
                }
                if (isAdd) {
                    [arrayFilter addObject:dict];
                }
            }
            @catch (NSException *e) {
                NSLog(@"%@",e);
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    
    
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}


+ (NSMutableArray*) queryScheduleByIdCategory:(int)categoryId inStart:(NSString *)startDate endDate:(NSString *)endDate from:(int)indexFrom numberPage:(int)count{
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byIdCategory:categoryId];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        NSDate *dateStart = nil;
        if (startDate != nil && ![startDate isEqualToString:@""]) {
            dateStart =[NSDate dateFormatDateDisplayFromString:startDate];
            
        }
        NSDate *dateEnd = nil;
        if (endDate != nil && ![endDate isEqualToString:@""]) {
            dateEnd = [NSDate dateFormatDateDisplayFromString:endDate];
        }
        
        for (NSMutableDictionary *dict in array) {
            NSString *strDateSchedue = [dict objectForKey:@"startDate"];
            strDateSchedue = [strDateSchedue substringToIndex:10];
            NSDate *dateSchedule = [NSDate dateFormatDateFromString:strDateSchedue];
            BOOL isAdd = YES;
            
            if (dateStart && [dateStart compare:dateSchedule] == NSOrderedDescending) {
                isAdd = NO;
            }
            if (isAdd && dateEnd && [dateEnd compare:dateSchedule] == NSOrderedAscending) {
                isAdd = NO;
            }
            if (isAdd) {
                [arrayFilter addObject:dict];
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}

+ (NSMutableArray*) queryScheduleByCategory:(NSMutableDictionary *)category inStart:(NSString *)startDate endDate:(NSString *)endDate from:(int)indexFrom numberPage:(int)count{
    
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byCategory:category];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        NSDate *dateStart = nil;
        if (startDate != nil && ![startDate isEqualToString:@""]) {
            dateStart =[NSDate dateFormatDateDisplayFromString:startDate];
            
        }
        NSDate *dateEnd = nil;
        if (endDate != nil && ![endDate isEqualToString:@""]) {
            dateEnd = [NSDate dateFormatDateDisplayFromString:endDate];
        }
        
        for (NSMutableDictionary *dict in array) {
            NSString *strDateSchedue = [dict objectForKey:@"startDate"];
            strDateSchedue = [strDateSchedue substringToIndex:10];
            NSDate *dateSchedule = [NSDate dateFormatDateFromString:strDateSchedue];
            BOOL isAdd = YES;
            
            if (dateStart && [dateStart compare:dateSchedule] == NSOrderedDescending) {
                isAdd = NO;
            }
            if (isAdd && dateEnd && [dateEnd compare:dateSchedule] == NSOrderedAscending) {
                isAdd = NO;
            }
            if (isAdd) {
                [arrayFilter addObject:dict];
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}

+ (NSMutableArray*) queryScheduleByFilterDict:(NSMutableDictionary *)filterDict from:(int)indexFrom numberPage:(int)count{
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byIdCategory:[[filterDict objectForKey:@"categoryId"] intValue]];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        BOOL isOK = YES; //satisfy the condition in filter array
        for (int i=0;i < [array count];i++) {
            NSMutableDictionary *content = [array objectAtIndex:i];
            if (![[content objectForKey:@"building"] isEqualToString:[filterDict objectForKey:@"building"]]) {
                isOK = NO;
            }
            if (isOK && ![[content objectForKey:@"service"] isEqualToString:[filterDict objectForKey:@"service"]]) {
                isOK = NO;
            }
            if (isOK && ![[content objectForKey:@"camp"] isEqualToString:[filterDict objectForKey:@"camp"]]) {
                isOK = NO;
            }
            if (isOK && ![[content objectForKey:@"unit"] isEqualToString:[filterDict objectForKey:@"unit"]]) {
                isOK = NO;
            }
            if (isOK && ![[content objectForKey:@"floor"] isEqualToString:[filterDict objectForKey:@"floor"]]) {
                isOK = NO;
            }
            if (isOK && ![[content objectForKey:@"room"] isEqualToString:[filterDict objectForKey:@"room"]]) {
                isOK = NO;
            }
            if (isOK) {
                [arrayFilter addObject:content];
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}

+ (NSMutableArray*) queryScheduleByItemId:(NSMutableDictionary *)filterDict from:(int)indexFrom numberPage:(int)count{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double timeInterval = [[userDefaults objectForKey:TIME_DURATION_DB_SERVER] doubleValue];
    NSTimeInterval timeIntervalLimited = [[[NSDate date] dateByAddingTimeInterval:-timeInterval] timeIntervalSince1970];
    
    CBLView* view = [[CouchBaseLiteLib sharedCouchBaseLite].database viewNamed: @"listScheduleByItemId"];
    if (!view.mapBlock) {
        // Register the map function, the first time we access the view:
        [view setMapBlock: MAPBLOCK({
            if ([doc[@"Table"] isEqualToString:kScheduleDocType] && doc[@"itemId"] && doc[SCHEDULE_MGMT_TYPE]){
                    emit(@[doc[@"itemId"],[NSNumber numberWithInt:[[doc objectForKey:SCHEDULE_MGMT_TYPE] intValue]]], doc);
            }
        }) reduceBlock: nil version: @"1"]; // bump version any time you change the MAPBLOCK body!
    }
    
    CBLQuery *query = [view query];
    query.startKey = @[[filterDict objectForKey:@"itemId"],[NSNumber numberWithInt:[[filterDict objectForKey:SCHEDULE_MGMT_TYPE] intValue]]];
    query.endKey = @[[filterDict objectForKey:@"itemId"],[NSNumber numberWithInt:[[filterDict objectForKey:SCHEDULE_MGMT_TYPE] intValue]]];
    query.skip = indexFrom;
    query.limit = count;
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (CBLQueryRow *row in query.rows) {
        double dateUpdated = [[row.document propertyForKey:@"dateUpdated"] doubleValue];
        if (dateUpdated >= timeIntervalLimited)
            [array addObject:[row.document.properties mutableCopy]];
    }
    
    [array sortUsingComparator:^(NSMutableDictionary *obj1, NSMutableDictionary *obj2){
        
        NSDate *date1 = [NSDate dateFormatDateFullFromString:[obj1 objectForKey:@"startDate"]];
        
        NSDate *date2 = [NSDate dateFormatDateFullFromString:[obj2 objectForKey:@"startDate"]];
        if (date1 && date2)
            return [date2 compare:date1];
        else
            return NSOrderedAscending;
        
    }];
    
    return array;
//    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
//    [arrayFilter addObjectsFromArray:array];
//    
//    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
//    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
//        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
//    }
//    return arrayResult;
}

// Returns a query for all the lists in a database.
+ (NSMutableArray*) queryScheduleByContractor:(NSString *)contractorId inStart:(NSString *)startDate endDate:(NSString *)endDate from:(int)indexFrom  numberPage:(int)count{
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        NSDate *dateStart = nil;
        if (startDate != nil && ![startDate isEqualToString:@""]) {
            dateStart =[NSDate dateFormatDateDisplayFromString:startDate];
            
        }
        NSDate *dateEnd = nil;
        if (endDate != nil && ![endDate isEqualToString:@""]) {
            dateEnd = [NSDate dateFormatDateDisplayFromString:endDate];
        }
        
        for (NSMutableDictionary *dict in array) {
            @try {
                
                NSString *userId = [dict objectForKey:@"userId"];
                NSString *_contractorId = [[dict objectForKey:@"personInCharge"] objectForKey:@"_id"];
                if ([_contractorId isEqualToString:contractorId] || [userId isEqualToString:contractorId])
                    ;
                else
                    continue;
                    
                NSString *strDateSchedue = [dict objectForKey:@"startDate"];
                strDateSchedue = [strDateSchedue substringToIndex:10];
                NSDate *dateSchedule = [NSDate dateFormatDateFromString:strDateSchedue];
                BOOL isAdd = YES;
                
                if (dateStart && [dateStart compare:dateSchedule] == NSOrderedDescending) {
                    isAdd = NO;
                }
                if (isAdd && dateEnd && [dateEnd compare:dateSchedule] == NSOrderedAscending) {
                    isAdd = NO;
                }
                if (isAdd) {
                    [arrayFilter addObject:dict];
                }
            }
            @catch (NSException *e) {
                NSLog(@"%@",e);
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    
    
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}

+ (NSMutableArray*) queryScheduleByIdCategory:(int)categoryId byContractor:(NSString *)contractorId inStart:(NSString *)startDate endDate:(NSString *)endDate from:(int)indexFrom numberPage:(int)count{
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byIdCategory:categoryId];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        NSDate *dateStart = nil;
        if (startDate != nil && ![startDate isEqualToString:@""]) {
            dateStart =[NSDate dateFormatDateDisplayFromString:startDate];
            
        }
        NSDate *dateEnd = nil;
        if (endDate != nil && ![endDate isEqualToString:@""]) {
            dateEnd = [NSDate dateFormatDateDisplayFromString:endDate];
        }
        
        for (NSMutableDictionary *dict in array) {
            
            NSString *userId = [dict objectForKey:@"userId"];
            NSString *_contractorId = [[dict objectForKey:@"personInCharge"] objectForKey:@"_id"];
            if ([_contractorId isEqualToString:contractorId] || [userId isEqualToString:contractorId])
                ;
            else
                continue;
            
            NSString *strDateSchedue = [dict objectForKey:@"startDate"];
            strDateSchedue = [strDateSchedue substringToIndex:10];
            NSDate *dateSchedule = [NSDate dateFormatDateFromString:strDateSchedue];
            BOOL isAdd = YES;
            
            if (dateStart && [dateStart compare:dateSchedule] == NSOrderedDescending) {
                isAdd = NO;
            }
            if (isAdd && dateEnd && [dateEnd compare:dateSchedule] == NSOrderedAscending) {
                isAdd = NO;
            }
            if (isAdd) {
                [arrayFilter addObject:dict];
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}

+ (NSMutableArray*) queryScheduleByCategory:(NSMutableDictionary *)category byContractor:(NSString *)contractorId inStart:(NSString *)startDate endDate:(NSString *)endDate from:(int)indexFrom numberPage:(int)count{
    
    NSMutableArray *array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byCategory:category];
    
    NSMutableArray *arrayFilter = [NSMutableArray arrayWithCapacity:1];
    
    if ([array count] > 0) {
        NSDate *dateStart = nil;
        if (startDate != nil && ![startDate isEqualToString:@""]) {
            dateStart =[NSDate dateFormatDateDisplayFromString:startDate];
            
        }
        NSDate *dateEnd = nil;
        if (endDate != nil && ![endDate isEqualToString:@""]) {
            dateEnd = [NSDate dateFormatDateDisplayFromString:endDate];
        }
        
        for (NSMutableDictionary *dict in array) {
            
            NSString *userId = [dict objectForKey:@"userId"];
            NSString *_contractorId = [[dict objectForKey:@"personInCharge"] objectForKey:@"_id"];
            if ([_contractorId isEqualToString:contractorId] || [userId isEqualToString:contractorId])
                ;
            else
                continue;
            
            NSString *strDateSchedue = [dict objectForKey:@"startDate"];
            strDateSchedue = [strDateSchedue substringToIndex:10];
            NSDate *dateSchedule = [NSDate dateFormatDateFromString:strDateSchedue];
            BOOL isAdd = YES;
            
            if (dateStart && [dateStart compare:dateSchedule] == NSOrderedDescending) {
                isAdd = NO;
            }
            if (isAdd && dateEnd && [dateEnd compare:dateSchedule] == NSOrderedAscending) {
                isAdd = NO;
            }
            if (isAdd) {
                [arrayFilter addObject:dict];
            }
        }
    }
    
    NSMutableArray *arrayResult = [NSMutableArray arrayWithCapacity:1];
    for (int i = indexFrom;i < indexFrom + count &&  i < [arrayFilter count]; i++) {
        [arrayResult addObject:[arrayFilter objectAtIndex:i]];
    }
    return arrayResult;
}

// Returns a query for all the lists in a database.
+ (NSMutableArray*) queryByContractor:(NSString *)contractorId ListsInDatabase: (CBLDatabase*)db {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double timeInterval = [[userDefaults objectForKey:TIME_DURATION_DB_SERVER] doubleValue];
    NSTimeInterval timeIntervalLimited = [[[NSDate date] dateByAddingTimeInterval:-timeInterval] timeIntervalSince1970];
    
    CBLView* view = [db viewNamed: @"listsSchedule"];
    if (!view.mapBlock) {
        // Register the map function, the first time we access the view:
        [view setMapBlock: MAPBLOCK({
            if ([doc[@"Table"] isEqualToString:kScheduleDocType])
                emit(doc, nil);
        }) reduceBlock: nil version: @"1"]; // bump version any time you change the MAPBLOCK body!
    }
    CBLQuery *query = [view query];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (CBLQueryRow *row in query.rows) {
        NSString *userId = [row.document.properties objectForKey:@"userId"];
        NSString *_contractorId = [[row.document.properties objectForKey:@"personInCharge"] objectForKey:@"_id"];
        if ([_contractorId isEqualToString:contractorId] || [userId isEqualToString:contractorId])
            ;
        else
            continue;
        double dateUpdated = [[row.document propertyForKey:@"dateUpdated"] doubleValue];
        if (dateUpdated >= timeIntervalLimited)
            [array addObject:[row.document.properties mutableCopy]];
    }
    [array sortUsingComparator:^(NSMutableDictionary *obj1, NSMutableDictionary *obj2){
        
        NSDate *date1 = [NSDate dateFormatDateFullFromString:[obj1 objectForKey:@"startDate"]];
        
        NSDate *date2 = [NSDate dateFormatDateFullFromString:[obj2 objectForKey:@"startDate"]];
        if (date1 && date2)
            return [date2 compare:date1];
        else
            return NSOrderedAscending;
        
    }];
    return array;
}

@end
